package com.mrogrape.notepad.activity.action.item;

import java.awt.event.ActionEvent;

import javax.swing.Action;

import com.mrogrape.notepad.activity.action.NotepadAction;
import com.mrogrape.notepad.data.ViewContext;
import com.mrogrape.notepad.ui.editor.TextEditor;
import com.mrogrape.util.StringUtils;


public class TrimEndOfLineMenuItemAction extends NotepadAction {

    /** serialVersionUID */
    private static final long serialVersionUID = -1L;

    public TrimEndOfLineMenuItemAction(){

	super.putValue(Action.NAME, "Remove End-of-line Blank Characters");
	super.putValue(Action.SHORT_DESCRIPTION, "Remove end-of-line blank characters in selection, If no selection then process all.");
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {

	TextEditor editor = ViewContext.getMainFrame().getCurrentTextEditor();
	if(editor == null||!editor.isEditable()||!editor.isEnabled()){
	    return;
	}

	String selection = editor.getSelectedText();
	boolean isAll = false;
	if(StringUtils.isEmpty(selection)){
	    isAll = true;
	    selection = editor.getText();
	}

	StringBuilder result = new StringBuilder();
	char[] chars = selection.toCharArray();
	boolean isLineEnd = true;

	for(int i = (chars.length - 1); i >= 0; i--){
	    char c = chars[i];

	    switch(c){
		case '\n':
		    isLineEnd = true;
		    result.append(c);
		    break;
		case '\t': case 0: case ' ':
		    if(!isLineEnd){
			result.append(c);
		    }
		    break;
		default:
		    if(c!='\r'){
			isLineEnd = false;
		    }
		    result.append(c);
		    break;
	    }
	}

	if(isAll){
	    editor.setText(result.reverse().toString());
	}else{
	    editor.replaceSelection(result.reverse().toString());
	}

    }
}
